package com.seven.good.service.impl;

import com.seven.good.config.ConfigNum;
import com.seven.good.dao.GoodMapper;
import com.seven.good.dao.GoodTypeMapper;
import com.seven.good.dao.HomePageMapper;
import com.seven.good.dto.GoodConditionDto;
import com.seven.good.enums.GoodStateEnum;
import com.seven.good.enums.ThemeEnum;
import com.seven.good.exception.*;
import com.seven.good.pojo.BidRecord;
import com.seven.good.pojo.Good;
import com.seven.good.pojo.HomePage;
import com.seven.good.service.GoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class GoodServiceImpl implements GoodService {


    // 注入配置了页面显示数目的类
    @Autowired
    ConfigNum configNum;

    @Autowired
    GoodMapper goodMapper;
    @Autowired
    GoodTypeMapper goodTypeMapper;

    @Autowired
    HomePageMapper homePageMapper;

    @Value(value = "${pageInfo.pageSize}")
    Integer pageSize;

    @Value(value = "${goodInfo.delayPeriod}")
    Integer delayPeriod;



    @Override
    public List<Good> listGoodsByCondition(GoodConditionDto condition, Integer currentPage) {
        List<Good> goods = null;
        try {
            goods = goodMapper.selectByCondition(condition, currentPage, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("数据库查询异常");
        }
        return goods;
    }

    @Override
    public List<Good> listGoodsByTypeOnToday(Integer goodType, Integer currentPage) {
        List<Good> goods = null;
        try {
            goods = goodMapper.selectByTypeOnToday(goodType, currentPage, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("数据库查询异常");
        }
        return goods;
    }

    @Override
    public Integer insertGoodAndGetGid(Good good,Long durationTime) throws GoodException{
        verifyGood(good);
        //后验证时长，可以避免重复验证开始时间
        if (durationTime != null && durationTime > 0) {
            Date endTime = new Date(good.getStartTime().getTime()+durationTime);
            good.setEndTime(endTime);
        } else {
            throw new GoodException("时长设置不合法");
        }
        //默认属性配置：状态；延时周期
        good.setGoodState(GoodStateEnum.TO_CHECK.getCode());
        good.setDelayPeriod(delayPeriod);
        good.setFlag(Byte.valueOf("0"));
        try {
            goodMapper.insertAndGetGid(good);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("数据库插入异常",e);
        }
        Integer gid = good.getGid();
        return gid;
    }
    /**
     * @ Description   :  验证商品信息
     * @ Author        :  lee
     * @ param        :     Good
     * @ exception    :     GoodException
     * @ CreateDate    :  2019/10/25 12:13
     */
    private void verifyGood(Good good) throws GoodException {
        String verifyString;
        Integer verifyInt;//Integer类型的临时接收参数
        Date verifyDate;//Date类型的临时接收参数
        if ((verifyString = good.getTitle()) == null || verifyString.length()<3) {
            throw new GoodException("商品标题不正确");
        }
        if ((verifyInt = good.getGoodType()) == null
                || goodTypeMapper.selectByPrimaryKey(verifyInt)==null) {
            throw new GoodException("商品类型错误");
        }
        if ((verifyInt = good.getStartPrice().intValue()) == null
                || verifyInt<0) {
            throw new GoodException("起拍价错误");
        }
        if ((verifyInt = good.getBuyerBond()) == null
                || verifyInt < 0) {
            throw new GoodException("保证金错误");
        }
        if ((verifyInt = good.getRangePrice()) == null
                || verifyInt < 0) {
            throw new GoodException("加价幅度错误");
        }
        if ((verifyInt = good.getReservePrice()) == null
                || verifyInt < 0) {
            throw new GoodException("保留价错误");
        }
        //要求拍卖时间在当前一个小时后
        if ((verifyDate= good.getStartTime()) == null
                || verifyDate.before(new Date(new Date().getTime()+3600000))) {
            throw new GoodException("起拍时间错误");
        }
    }

    @Override
    public void updateUrlByGid(String url, Integer gid) {
        try {
            goodMapper.updateUrlByGid(url,gid);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("数据库更新异常");
        }
    }

    @Override
    @Cacheable(value = "recommend", key = "'circuseenum'")
    public List<Good> listGoodsByCircuseeNo() {
        try {
            return goodMapper.listGoodsByCircuseeNo(configNum.getCircuseenum());
        } catch (Exception e) {
            throw new GoodNotFoundException();
        }
    }

    @Override
    @Cacheable(value = "recommend", key = "'bidnum'")
    public List<Good> listGoodsByBidNo() {
        try {
            return goodMapper.listGoodsByBidNo(configNum.getBidnum());
        } catch (Exception e) {
            throw new GoodNotFoundException();
        }
    }

    @Override
    @Cacheable(value = "recommend", key = "'signupnum'")
    public List<Good> listGoodsBySignUpNo() {

        try {

            return goodMapper.listGoodsBySignUpNo(configNum.getSignupnum());
        } catch (Exception e) {
            throw new GoodNotFoundException("系统维护中");
        }
    }

    @Override
    //@Cacheable(value = "good",key = "#gid")
    public Good getGoodByGid(Integer gid) {
        try {
            Good good=goodMapper.selectByPrimaryKey(gid);
            return good;
        }catch (DaoException e){
            e.printStackTrace();
            throw new ServiceException("系统维护中");
        }

    }

    @Override
    public void modifyRemindNoByGid(Integer gid) {
        try {
            goodMapper.updateRemindNoByGid(gid);
        }catch (DaoException e){
            e.printStackTrace();
            throw new ServiceException("系统维护中");
        }
    }

    @Override
    public HomePage getOneTheme() {
        return homePageMapper.getOneRandomTheme(ThemeEnum.OneThemePage.getNum());
    }

    @Override
    public Good getExGood() {
        return goodMapper.getExGood();
    }

    @Override
    public boolean updateEndtime(Integer gid) {

        try {
            if (goodMapper.updateEndtime(gid) > 0) {
                return true;
            }
        } catch (Exception e) {
            throw new AuctionException("更新商品时间出错");
        }
        return false;
    }

    @Override
    public Good getGoodById(Integer gid) {
        try {
            return goodMapper.selectByPrimaryKey(gid);
        } catch (Exception e) {
            throw new AuctionException("竞拍室获取商品出错");
        }
    }

    public void modifyCircuseeNoByGid(Integer gid) {
        try {
            goodMapper.updateCircuseeNoByGid(gid);
        }catch (DaoException e){
            e.printStackTrace();
            throw new ServiceException("系统维护中");
        }
    }

    @Override
    public void modifySignupNoByGid(Integer gid) {
        try {
            goodMapper.updateSignupNoByGid(gid);
        }catch (DaoException e){
            e.printStackTrace();
            throw new ServiceException("系统维护中");
        }
    }

    /**
     * @Description：更新数据库当前价格和竞拍次数
     * @Author: ytj
     * @param: bidRecord 竞价记录
     * @CreateDate:  19/10/26
     */
    @Override
    public void updateNowPriceAndBidNo(BidRecord bidRecord) {
        try {
            goodMapper.updateNowPriceAndBidNo(bidRecord.getGid(),bidRecord.getBidPrice());
        } catch (Exception e) {
            throw new AuctionException("根据数据库当前价格和竞拍次数出现异常");
        }
    }
}